package com.ruoyi.api.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.api.vo.CartVo;
import com.ruoyi.api.vo.SelectCartVo;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.shop.domain.ShopCouponCode;
import com.ruoyi.shop.domain.ShopProduct;
import com.ruoyi.shop.domain.ShopUserCart;
import com.ruoyi.shop.domain.ShopUserOpenid;
import com.ruoyi.shop.service.IShopCouponCodeService;
import com.ruoyi.shop.service.IShopProductService;
import com.ruoyi.shop.service.IShopUserCartService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author Alan Zhang
 * @Date 2021/10/6 16:30
 */
@Api(tags = "购物车")
@RestController
@RequestMapping("/api/cart")
public class ApiCartController extends ApiBaseController{
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private IShopUserCartService shopUserCartService;
    @Autowired
    private IShopProductService shopProductService;
    @Autowired
    private IShopCouponCodeService shopCouponCodeService;

    /**
     * 购物车
     */
    @ApiOperation(value = "购物车")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", name = "token", value = "用户token", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query",name = "pageSize", value = "数量", dataType = "Integer"),
            @ApiImplicitParam(paramType = "query",name = "pageNum", value = "页码", dataType = "Integer"),
    })
    @GetMapping("/index")
    public AjaxResult cart(){
        //分页取 10
        ShopUserOpenid shopUserOpenid = shopUserIdByToken();
        ShopUserCart param = new ShopUserCart();
        param.setUserId(shopUserOpenid.getUserId());

        startPage();
        List<ShopUserCart> cartList = shopUserCartService.selectShopUserCartList(param);

        Map<String,Object> map = getCart();

        return AjaxResult.success(cartList).put("cartInfo", map);
    }

    private Map<String,Object> getCart(){
        Map<String, Object> resultObj = new HashMap();

        ShopUserOpenid shopUserOpenid = shopUserIdByToken();
        //获取购物车统计信息
        ShopUserCart param = new ShopUserCart();
        param.setUserId(shopUserOpenid.getUserId());

        List<ShopUserCart> cartList = shopUserCartService.selectShopUserCartList(param);

        Integer goodsCount = 0;
        BigDecimal goodsAmount = new BigDecimal(0.00);
        Integer checkedGoodsCount = 0;
        BigDecimal checkedGoodsAmount = new BigDecimal(0.00);
        for (ShopUserCart cartItem : cartList) {
            goodsCount += cartItem.getProductCount();
            goodsAmount = goodsAmount.add(cartItem.getProductPrice().multiply(new BigDecimal(cartItem.getProductCount())));
            if (null != cartItem.getSelected() && 1 == cartItem.getSelected()) {
                checkedGoodsCount += cartItem.getProductCount();
                checkedGoodsAmount = checkedGoodsAmount.add(cartItem.getProductPrice().multiply(new BigDecimal(cartItem.getProductCount())));
            }
        }
        ShopCouponCode couponParam = new ShopCouponCode();
        couponParam.setUserId(shopUserOpenid.getUserId());
        couponParam.setStatus(ShopCouponCode.STATUS_NORMAL);
        List<ShopCouponCode> couponVos = shopCouponCodeService.selectShopCouponCodeList(couponParam);
        List<ShopCouponCode> couponInfoList = new ArrayList();
       for (ShopCouponCode couponCode: couponVos){

       }

        resultObj.put("couponInfoList", couponInfoList);
        resultObj.put("cartList", cartList);

        Map<String, Object> cartTotal = new HashMap();
        cartTotal.put("goodsCount", goodsCount);
        cartTotal.put("goodsAmount", goodsAmount);
        cartTotal.put("checkedGoodsCount", checkedGoodsCount);
        cartTotal.put("checkedGoodsAmount", checkedGoodsAmount);

        resultObj.put("cartTotal", cartTotal);
        return resultObj;
    }

    /**
     * 购物车商品数量
     */
    @ApiOperation(value = "购物车商品数量")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", name = "token", value = "用户token", required = true, dataType = "String"),
    })
    @GetMapping("/info")
    public AjaxResult info(){
        ShopUserOpenid shopUserOpenid = shopUserIdByToken();
        ShopUserCart param = new ShopUserCart();
        param.setUserId(shopUserOpenid.getUserId());

        List<ShopUserCart> cartList = shopUserCartService.selectShopUserCartList(param);
        HashMap<Long, Integer> cartMap = new HashMap<>();
        for(ShopUserCart entity:cartList){
            cartMap.put(entity.getProductId() , entity.getProductCount());
        }
        return AjaxResult.success(cartMap);
    }

    /**
     * 批量加入购物车
     */
    @ApiOperation(value = "批量加入购物车")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", name = "token", value = "用户token",required = true, dataType = "String"),
    })
    @PostMapping("/batchAdd")
    public AjaxResult batchAddCart(@RequestBody String data){

        logger.info("data ========"+data);
        if(StringUtils.isEmpty(data)){
            return AjaxResult.error("错误参数");
        }
        ShopUserOpenid shopUserOpenid = shopUserIdByToken();

        JSONObject jsonObject = JSON.parseObject(data);
        JSONArray jsonArray = jsonObject.getJSONArray("data");
        List<CartVo> cartVoList = jsonArray.toJavaList(CartVo.class);

        List<ShopUserCart> userCartList = new ArrayList<>();
        StringBuilder sb = new StringBuilder();
        for (CartVo cartVo:cartVoList){
            if(cartVo.getQty() <= 0){
                logger.info("过滤=={} {}",cartVo.getProductId() , cartVo.getQty());
                continue;
            }

            ShopProduct product = shopProductService.selectShopProductById(cartVo.getProductId());
            if(2 == product.getStatus()){
                sb.append(product.getTitle()).append(" 已下架");
                continue;
            }
            if(product.getStock() < cartVo.getQty()){
                sb.append(product.getTitle()).append(" 库存不足");
                continue;
            }

            ShopUserCart param = new ShopUserCart();
            param.setUserId(shopUserOpenid.getUserId());
            param.setProductId(cartVo.getProductId());

            List<ShopUserCart> dbCartList = shopUserCartService.selectShopUserCartList(param);
            if(dbCartList.size() == 0){
                ShopUserCart userCart = new ShopUserCart();
                userCart.setUserId(shopUserOpenid.getUserId());
                userCart.setProductId(product.getId());
                userCart.setProductCount(cartVo.getQty());
                userCart.setProductPrice(product.getPrice());
                userCart.setWithRefund(1);
                userCart.setSelected(1);
                userCartList.add(userCart);

            } else {
                ShopUserCart userCart = dbCartList.get(0);
                userCart.setProductCount(cartVo.getQty());

                int rows = shopUserCartService.updateShopUserCart(userCart);
            }
        }

        if(userCartList.size() > 0) {
            int rows = shopUserCartService.batchShopUserCart(userCartList);
        }
        return AjaxResult.success("加入购物车成功 " + sb.toString());
    }


    /**
     * 加入购物车
     */
    @ApiOperation(value = "加入购物车")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", name = "token", value = "用户token",required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query",name = "productId", value = "商品Id",required = true, dataType = "Long"),
            @ApiImplicitParam(paramType = "query",name = "qty", value = "数量",required = true, dataType = "Integer"),
    })
    @GetMapping("/add")
    public AjaxResult addCart(@NotNull Long productId, @NotNull Integer qty){
        if(qty <= 0){
            return AjaxResult.error("数量必须大于0");
        }
        ShopUserOpenid shopUserOpenid = shopUserIdByToken();

        ShopUserCart param = new ShopUserCart();
        param.setUserId(shopUserOpenid.getUserId());
        param.setProductId(productId);

        List<ShopUserCart> userCartList = shopUserCartService.selectShopUserCartList(param);

        if(userCartList.size() == 0){
            ShopProduct product = shopProductService.selectShopProductById(productId);
            if(2 == product.getStatus()){
                return AjaxResult.error("该商品已下架");
            }
            if(product.getStock() < qty){
                return AjaxResult.error("库存不足");
            }
            ShopUserCart userCart = new ShopUserCart();
            userCart.setUserId(shopUserOpenid.getUserId());
            userCart.setProductId(productId);
            userCart.setProductCount(qty);
            userCart.setProductPrice(product.getPrice());
            userCart.setWithRefund(1);
            userCart.setSelected(1);

            int rows = shopUserCartService.insertShopUserCart(userCart);
            if(rows > 0){
                return AjaxResult.success("加入购物车成功");
            } else {
                return AjaxResult.error("加入购物车失败");
            }
        } else if(userCartList.size() == 1){
            ShopUserCart userCart = userCartList.get(0);

            userCart.setProductCount(qty);

            int rows = shopUserCartService.updateShopUserCart(userCart);
            if(rows > 0){
                return AjaxResult.success("更新购物车成功");
            } else {
                return AjaxResult.error("更新购物车失败");
            }
        } else {
            return AjaxResult.error("失败，多条信息。");
        }
    }

    /**
     * 减少商品到购物车
     */
    @ApiOperation(value = "减少商品到购物车")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", name = "token", value = "用户token",required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query",name = "productId", value = "商品Id",required = true, dataType = "Long"),
            @ApiImplicitParam(paramType = "query",name = "qty", value = "数量",required = true, dataType = "Integer"),
    })
    @PostMapping("minus")
    public Object minus(Long productId, Integer qty) {

        ShopUserOpenid shopUserOpenid = shopUserIdByToken();

        ShopUserCart param = new ShopUserCart();
        param.setUserId(shopUserOpenid.getUserId());
        param.setProductId(productId);

        List<ShopUserCart> userCartList = shopUserCartService.selectShopUserCartList(param);

        if(userCartList.size() == 0){
            //ShopProduct product = shopProductService.selectShopProductById(productId);

            ShopUserCart shopUserCart =  userCartList.get(0);
            shopUserCart.setProductCount(qty);
            shopUserCartService.updateShopUserCart(shopUserCart);
        }
        return AjaxResult.success();
    }

    /**
     * 删除购物车商品
     */
    @ApiOperation(value = "删除购物车商品")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", name = "token", value = "用户token",required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query",name = "productId", value = "商品Id",required = true, dataType = "String"),
    })
    @GetMapping("/remove")
    public AjaxResult removeCart(String[] productId) {
        if (productId == null) {
            return AjaxResult.error("请选择需要删除的商品");
        }
        ShopUserOpenid shopUserOpenid = shopUserIdByToken();

        int rows = shopUserCartService.deleteShopUserCartByProductIds(shopUserOpenid.getUserId(), productId);

        if (rows > 0) {
            return AjaxResult.success("删除的商品成功");
        } else {
            return AjaxResult.error("删除的商品失败");
        }
    }


    /**
     * 是否选择商品，如果已经选择，则取消选择，批量操作
     */
    @ApiOperation(value = "是否选择商品")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", name = "token", value = "用户token",required = true, dataType = "String"),
    })
    @PostMapping("/selected")
    public AjaxResult selected(@RequestBody SelectCartVo selectCartVo) {
        ShopUserOpenid shopUserOpenid = shopUserIdByToken();

        int rows = shopUserCartService.updateCheck(selectCartVo.getProductIds(), selectCartVo.getIsChecked(), shopUserOpenid.getUserId());
        if(rows > 0){
            return AjaxResult.success();
        } else {
            return AjaxResult.error();
        }

    }

    public static void main(String[] args) {
//        CartVo s = new CartVo();
//        s.setProductId(1L);
//        s.setQty(3);
//        CartVo ss = new CartVo();
//        ss.setProductId(2L);
//        ss.setQty(1);
//        List<CartVo> list= new ArrayList<>();
//        list.add(s);
//        list.add(ss);
//        System.out.println(JSONObject.toJSON(list));

        SelectCartVo selectCartVo= new SelectCartVo();
        selectCartVo.setIsChecked(0);

        selectCartVo.setProductIds(new String[]{"1", "2"});
        System.out.println(JSONObject.toJSON(selectCartVo));
    }
}
